package cn.afei.cloud.utils.result;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.Map;

/**
 * 返回数据
 *
 * @author Mark sunlightcs@gmail.com
 */
public class ResultDataVo extends HashMap<String, Object> {
    private static final long serialVersionUID = 1L;

    public ResultDataVo() {
        put("code", 0);
        put("msg", "success");
    }

    public ResultDataVo setData(Object data) {
        put("data", data);
        return this;
    }

    // 利用fastjson进行反序列化
    public <T> T getData(TypeReference<T> typeReference) {
        // 默认是map
        Object data = get("data");
        ObjectMapper mapper = new ObjectMapper();
        String jsonString = null;
        try {
            jsonString = mapper.writeValueAsString(data);
            return mapper.readValue(jsonString, typeReference);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return null;
    }

    // 利用fastjson进行反序列化
    public <T> T getData(String key, TypeReference<T> typeReference) {
        // 默认是map
        Object data = get(key);
        ObjectMapper mapper = new ObjectMapper();
        try {
            String jsonString = mapper.writeValueAsString(data);
            return mapper.readValue(jsonString, typeReference);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static ResultDataVo error() {
        return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常，请联系管理员");
    }

    public static ResultDataVo error(String msg) {
        return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
    }

    public static ResultDataVo error(int code, String msg) {
        ResultDataVo resultDataVo = new ResultDataVo();
        resultDataVo.put("code", code);
        resultDataVo.put("msg", msg);
        return resultDataVo;
    }

    public static ResultDataVo ok(String msg) {
        ResultDataVo resultDataVo = new ResultDataVo();
        resultDataVo.put("msg", msg);
        return resultDataVo;
    }

    public static ResultDataVo ok(Map<String, Object> map) {
        ResultDataVo resultDataVo = new ResultDataVo();
        resultDataVo.putAll(map);
        return resultDataVo;
    }

    public static ResultDataVo ok() {
        return new ResultDataVo();
    }

    @Override
    public ResultDataVo put(String key, Object value) {
        super.put(key, value);
        return this;
    }

    public Integer getCode() {

        return (Integer) this.get("code");
    }

}
